 
package steven.im.data;   

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import steven.im.bean.ItemBean;
import steven.im.util.IMUtil;
  
/**   
 *@author: Steven.amaxgs@gmail.com
 *@version:1.0   
 *@createdata:Nov 14, 2011 3:27:16 PM
 */

public class PersistenceXMLData implements IPersistenceData {

	@Override
	public ItemBean addItem(ItemBean item) {
		String dir=System.getProperty("user.dir")+"\\xml-data\\imdata.xml";
		SAXReader reader=new SAXReader();
		FileInputStream in=null;
		Document doc=null;
		
		try {
			in = new FileInputStream(dir);
			doc=reader.read(in);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Element rootEmt=doc.getRootElement();
		String id=UUID.randomUUID().toString();
		item.setId(id);
		Element itemEmt=rootEmt.addElement("item").addAttribute("id", item.getId()).addAttribute("category","1");
		itemEmt.addElement("name").addText(item.getName());
		itemEmt.addElement("user1").addText(item.getUser1());
		itemEmt.addElement("user2").addText(item.getUser2());
		itemEmt.addElement("password").addText(item.getPassword());
		itemEmt.addElement("mail1").addText(item.getMail1());
		itemEmt.addElement("mail2").addText(item.getMail2());
		itemEmt.addElement("url").addText(item.getUrl());
		itemEmt.addElement("question1").addText(item.getQuestion1());
		itemEmt.addElement("answer1").addText(item.getAnswer1());
		itemEmt.addElement("question2").addText(item.getQuestion2());
		itemEmt.addElement("answer2").addText(item.getAnswer2());
		itemEmt.addElement("question3").addText(item.getQuestion3());
		itemEmt.addElement("answer3").addText(item.getAnswer3());
		itemEmt.addElement("updatetime").addText(IMUtil.getDateTime(item.getUpdatetime()));
		itemEmt.addElement("createtime").addText(IMUtil.getDateTime(item.getCreatetime()));
		itemEmt.addElement("updatetimes").addText(String.valueOf(item.getUpdatetimes()));
		itemEmt.addElement("millis").addText(String.valueOf(item.getMillis()));
		
		FileWriter fw;
		XMLWriter xmlWriter;
		try {
			fw = new FileWriter(dir);
			xmlWriter=new XMLWriter(fw);
			OutputFormat format=OutputFormat.createPrettyPrint();
			xmlWriter=new XMLWriter(fw, format);
			xmlWriter.write(doc);
			xmlWriter.close();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return item;
	}

}
  